package hzau.utils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import hzau.constants.ESconstants;
import hzau.dao.PaperDao;
import hzau.dao.QuestionDao;
import hzau.dao.SelectionQuestionDao;
import hzau.pojo.Paper;
import hzau.pojo.question.Question;
import hzau.pojo.question.SelectionQuestion;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
@Configuration
//@SpringBootTest
public class ESUtil {


@Autowired
    PaperDao paperDao;
@Autowired
    SelectionQuestionDao selectionQuestionDao;
@Autowired
    QuestionDao questionDao;
    RestHighLevelClient client=new RestHighLevelClient(RestClient.builder(HttpHost.create("http://192.168.192.148:9200")));

    public void bulkImportSelections() throws IOException {
        LambdaQueryWrapper<Paper> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Paper::getExpired,1);
        List<Paper> papers = paperDao.selectList(lambdaQueryWrapper);
        BulkRequest request=new BulkRequest();
        for(Paper paper:papers){
            LambdaQueryWrapper<SelectionQuestion> lqw=new LambdaQueryWrapper<>();
            lqw.eq(SelectionQuestion::getPaperId,paper.getId());
            List<SelectionQuestion> selectionQuestions = selectionQuestionDao.selectList(lqw);
            for (SelectionQuestion selectionQuestion : selectionQuestions) {
                request.add(new IndexRequest("selections").
                        id(selectionQuestion.getId().toString()).
                        source(JSON.toJSONString(selectionQuestion), XContentType.JSON));
        }

        }
        client.bulk(request, RequestOptions.DEFAULT);
    }

    public void bulkImportQuestion() throws IOException {
        LambdaQueryWrapper<Paper> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Paper::getExpired,1);
        List<Paper> papers = paperDao.selectList(lambdaQueryWrapper);
        BulkRequest request=new BulkRequest();
        for(Paper paper:papers){
            LambdaQueryWrapper<Question> lqw=new LambdaQueryWrapper<>();
            lqw.eq(Question::getPaperId,paper.getId());
            List<Question> questions = questionDao.selectList(lqw);
            for (Question question : questions) {
                request.add(new IndexRequest("questions").
                        id(question.getId().toString()).
                        source(JSON.toJSONString(question), XContentType.JSON));
            }

        }
        client.bulk(request, RequestOptions.DEFAULT);
    }

    public void ImportWord(String str) throws IOException {
        HashMap<String,String> hashMap =new HashMap<>();
        hashMap.put("description",str);
        IndexRequest request=new IndexRequest("word").id("1");
        request.source(JSON.toJSONString(hashMap),XContentType.JSON);


        client.index(request, RequestOptions.DEFAULT);
    }
//    @Test
    public void deleteSelect() throws IOException {
        DeleteIndexRequest request=new DeleteIndexRequest("selections");

        client.indices().delete(request, RequestOptions.DEFAULT);
    }
//    @Test
    public void deleteQuestion() throws IOException {
        DeleteIndexRequest request=new DeleteIndexRequest("questions");

        client.indices().delete(request, RequestOptions.DEFAULT);
    }

    public void deleteWord() throws IOException {
        DeleteIndexRequest request=new DeleteIndexRequest("word");

        client.indices().delete(request, RequestOptions.DEFAULT);
    }
//    @Test
    public void creatESelect() throws IOException {
        CreateIndexRequest request=new CreateIndexRequest("selections");
        request.source(ESconstants.SELECTION_CREATE,XContentType.JSON);
        client.indices().create(request, RequestOptions.DEFAULT);
    }

    public void creatESWord() throws IOException {
        CreateIndexRequest request=new CreateIndexRequest("word");
        request.source(ESconstants.WORD_DESCRIPTION,XContentType.JSON);
        client.indices().create(request, RequestOptions.DEFAULT);
    }
//    @Test
    public void creatESQuestion() throws IOException {
        CreateIndexRequest request=new CreateIndexRequest("questions");
        request.source(ESconstants.QUESTION_CREATE,XContentType.JSON);
        client.indices().create(request, RequestOptions.DEFAULT);
    }
    public ArrayList<SelectionQuestion> selectionMatch(String description) throws IOException {
        SearchRequest request=new SearchRequest("selections");
        request.source().query(QueryBuilders.matchQuery("description",description)).size(5);
        SearchResponse response=client.search(request,RequestOptions.DEFAULT);
        SearchHits searchHits=response.getHits();
        long total =searchHits.getTotalHits().value;
        SearchHit[] hits=searchHits.getHits();
        ArrayList<SelectionQuestion> selectionQuestions=new ArrayList<>();
        for (SearchHit hit : hits) {
            String json=hit.getSourceAsString();
            SelectionQuestion selectionQuestion = JSON.parseObject(json, SelectionQuestion.class);
            selectionQuestion.setScore((double) hit.getScore());
            selectionQuestions.add(selectionQuestion);

        }
        return selectionQuestions;
    }
//    @Test
    public ArrayList<Question> QuestionMatch(String description) throws IOException {
        SearchRequest request=new SearchRequest("questions");
        request.source().query(QueryBuilders.matchQuery("description",description)).size(5);
        SearchResponse response=client.search(request,RequestOptions.DEFAULT);
        SearchHits searchHits=response.getHits();
        long total =searchHits.getTotalHits().value;
        SearchHit[] hits=searchHits.getHits();
        ArrayList<Question> Questions=new ArrayList<>();
        for (SearchHit hit : hits) {
            String json=hit.getSourceAsString();
            Question question = JSON.parseObject(json, Question.class);
            question.setScore((double) hit.getScore());
            Questions.add(question);
            System.out.println(question);
        }
        return Questions;
    }
    public Double WordMatch(String description) throws IOException {
        SearchRequest request=new SearchRequest("word");
        request.source().query(QueryBuilders.matchQuery("description",description));
        SearchResponse response=client.search(request,RequestOptions.DEFAULT);
        SearchHits searchHits=response.getHits();
//        System.out.println(searchHits.toString());
        long total =searchHits.getTotalHits().value;
        System.out.println(total);
        SearchHit[] hits=searchHits.getHits();
        SearchHit hit=  hits[0];
        return Double.valueOf(hit.getScore());
//            String json=hit.getSourceAsString();
////            Question question = JSON.parseObject(json, Question.class);
////            question.setScore((double) hit.getScore());
//
//            System.out.println(json);

//        return Questions;
    }

}
